package client

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"onerk4/zg5yk/ordering/common/proto/user"
)

type UserHandler func(ctx context.Context, in user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handler UserHandler) (interface{}, error) {
	// 1.连接
	conn, err := grpc.Dial("127.0.0.1:8081", grpc.WithInsecure())
	if err != nil {
		fmt.Printf("连接异常： %s\n", err)
		return nil, err
	}
	defer conn.Close()
	c := user.NewUserClient(conn)
	res, err := handler(ctx, c)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func UserLogin(ctx context.Context, req *user.UserLoginRequest) (*user.UserLoginResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		login, err := in.UserLogin(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserLoginResponse), nil
}

func ReceiveCoupon(ctx context.Context, req *user.ReceiveCouponRequest) (*user.ReceiveCouponResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		login, err := in.ReceiveCoupon(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.ReceiveCouponResponse), nil
}

func ShowCoupon(ctx context.Context, req *user.ShowCouponRequest) (*user.ShowCouponResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		login, err := in.ShowCoupon(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.ShowCouponResponse), nil
}
